package org.lex.expression;

import java.util.Stack;

public class ExpressionCalculator {
	public Number calculate(PostfixExpression pe) {
		Stack<Operand> stack = new Stack<Operand>();
		Stack<Element> postfix = pe.getPostfix();
		while (false == postfix.empty()) {
			Element n = postfix.pop();
			if (true == n.isOperand()) {
				stack.push(new Operand(n.getImage()));
				continue;
			} else if (true == n.isOperator()) {
				Operand second = stack.pop();
				Operand first = stack.pop();
				Operand result = ((Operator) n).operate(first, second);
				stack.push(result);
			} else {
				System.err.println("Unkown node: " + n);
				return Operand.NA.getValue();
			}
		}
		return stack.pop().getValue();
	}
}
